package com.concurrency.example.factory.property;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 咖啡配合配置文件的简单工厂
 */
public class CoffeeFactory {
    private static Map<String, Coffee> map = new HashMap<>();

    //静态代码块初始化操作
    static {
        Properties properties = new Properties();
        InputStream is = CoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");

        try{
            properties.load(is);

            Set<Object> keys = properties.keySet();

            for (Object key: keys) {
                String className = properties.getProperty((String) key);

                Class<?> clazz = Class.forName(className);
                Object object = clazz.newInstance();

                map.put((String) key, (Coffee) object);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Coffee createCoffee(String name){
        return map.get(name);
    }
}
